<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

use service\DataService;
use service\NodeService;
use think\Db;
use service\WechatService;


function reserve_num($num,$reserve=2){
    return sprintf("%.$reserve".'f',$num);
}

function check($data, $rule = NULL, $ext = NULL)
{
    $data = trim(str_replace(PHP_EOL, '', $data));

    if (empty($data)) {
        return false;
    }
    $validate['require'] = '/.+/';
    $validate['url'] = '/^http(s?):\\/\\/(?:[A-za-z0-9-]+\\.)+[A-za-z]{2,4}(?:[\\/\\?#][\\/=\\?%\\-&~`@[\\]\':+!\\.#\\w]*)?$/';
    $validate['currency'] = '/^\\d+(\\.\\d+)?$/';
    $validate['number'] = '/^\\d+$/';
    $validate['zip'] = '/^\\d{6}$/';
    $validate['cny'] = '/^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){1,2})?$/';
    $validate['integer'] = '/^[\\+]?\\d+$/';
    $validate['double'] = '/^[\\+]?\\d+(\\.\\d+)?$/';
    $validate['english'] = '/^[A-Za-z]+$/';
    $validate['idcard'] = '/^([0-9]{15}|[0-9]{17}[0-9a-zA-Z])$/';
    $validate['truename'] = '/^[\\x{4e00}-\\x{9fa5}]{2,4}$/u';
    $validate['account'] = '/^[0-9a-zA-Z_]{3,15}$/';
    $validate['username'] = '/^[0-9a-z_]{3,15}$/';
    $validate['email'] = '/^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$/';
    $validate['phone'] = '/^(((1[0-9][0-9]{1})|159|153)+\\d{8})$/';
    $validate['password'] = '/^[a-zA-Z0-9_\\@\\#\\$\\%\\^\\&\\*\\(\\)\\!\\,\\.\\?\\-\\+\\|\\=]{6,16}$/';
    $validate['xnb'] = '/^[a-zA-Z]$/';

    if (isset($validate[strtolower($rule)])) {
        $rule = $validate[strtolower($rule)];
        return preg_match($rule, $data);
    }
    $Ap = '\\x{4e00}-\\x{9fff}' . '0-9a-zA-Z\\@\\#\\$\\%\\^\\&\\*\\(\\)\\!\\,\\.\\?\\-\\+\\|\\=';
    $Cp = '\\x{4e00}-\\x{9fff}';
    $Dp = '0-9';
    $Wp = 'a-zA-Z';
    $Np = 'a-z';
    $Tp = '@#$%^&*()-+=';
    $_p = '_';
    $pattern = '/^[';
    $OArr = str_split(strtolower($rule));
    in_array('a', $OArr) && ($pattern .= $Ap);
    in_array('c', $OArr) && ($pattern .= $Cp);
    in_array('d', $OArr) && ($pattern .= $Dp);
    in_array('w', $OArr) && ($pattern .= $Wp);
    in_array('n', $OArr) && ($pattern .= $Np);
    in_array('t', $OArr) && ($pattern .= $Tp);
    in_array('_', $OArr) && ($pattern .= $_p);
    isset($ext) && ($pattern .= $ext);
    $pattern .= ']+$/u';
    return preg_match($pattern, $data);
}

function encrypt($string)
{
    return md5($string);
}
function get_order_status($status){
    $txt = '';
    switch ($status){
        case 1:
            $txt = '申请中';
            break;
        case 2:
            $txt = '已通过';
            break;
        case 3:
            $txt = '已拒绝';
    }
    return $txt;
}


function shuffle_assoc($list)
{
    if (!is_array($list)) return $list;
    $keys = array_keys($list);
    shuffle($keys);
    $random = array();
    foreach ($keys as $key)
        $random[$key] = $list[$key];
    return $random;
}

function getByIdAddress($id)
{
    return Db::name('sys_address')->where(['id' => $id])->value('area_name');
}

/*
 * $uid  用户id
 * $type 分佣类型
 * $money 操作金额
 * $content 分佣说明
 *  $extends  额外的补充
 *  $orderId  orderID
 * */

function replace_img_url($img_url)
{
    $parse_path = parse_url($img_url);
    if (!empty($parse_path['path'])) {
        $new_path = 'http://' . $_SERVER['HTTP_HOST'] . $parse_path['path'];
        return $new_path;
    }
}

/**
 *  * 获取美元人民币汇率
 *  * @return float
 *  */
function getRate()
{

}


function reserved($money){
   return sprintf("%.2f",$money);
}

function mlog($uid, $type, $money, $content, $extends = '', $orderId = 0, $status = 1,$fromid = 0)
{
    $before = Db::name('store_member')->where(['id' => $uid])->value($type);
    $res[] = Db::name('store_member')->where(['id' => $uid])->setInc($type, $money);
    if($type == 'spread_integral'){
        $money = -$money;
    }
    $res[] = Db::name('bags_log')->insert([
        'uid' => $uid,
        'type' => $type,
        'money' => $money,
        'before' => $before,
        'content' => $content,
        'extends' => $extends,
        'status' => $status,
        'create_time' => time(),
        'orderId' => $orderId,
        'fromid' => $fromid,
    ]);
    return $res;
}

function shopmlog($uid, $type, $money, $content, $extends = '', $orderId = 0, $status = 1,$fromid = 0)
{
    $before = Db::name('store_shops')->where(['id' => $uid])->value($type);
    $res[] = Db::name('store_shops')->where(['id' => $uid])->setInc($type, $money);
    $res[] = Db::name('bags_log')->insert([
        'uid' => $uid,
        'type' => $type,
        'money' => $money,
        'before' => $before,
        'content' => $content,
        'extends' => $extends,
        'status' => $status,
        'create_time' => time(),
        'orderId' => $orderId,
        'fromid' => $fromid,
    ]);
    return $res;
}


function getHashOrderInfo($orderid){
    return  Db::name('store_order_c2c')->where('id',$orderid)->value('order_no') ?? Db::name('store_order')->where('id',$orderid)->value('order_no');
}
//获取交易订单
function getC2cOrderPayTime($orderid){
    $orderInfo = Db::name('store_order_c2c')->where(['id'=>$orderid])->find();
    if(!$orderInfo){
        return false;
    }
    if($orderInfo['type'] ==1 ){
        //买入订单
       $result = Db::name('store_c2c_relation')->where(['orderid'=>$orderid])->find();
    }elseif($orderInfo['type'] == 2){
        //卖出订单
        $result = Db::name('store_c2c_relation')->where(['orderid'=>$orderInfo['other_order_id']])->find();
    }
    return $result;
}

/*发送短信*/
function sendMobileMessage($mobile, $content, $template_id = 0)
{
    $obj = new service\SmsApi();
    if ($template_id > 0) {
        //变量模板
        if ($template_id == 0) trigger_error('缺少短信模板id');
        return $obj->send($mobile, $content, $template_id);
    } else {
        //全文模板
        return $obj->sendAll($mobile, $content);
    }


}

//调用微信支付  调用页面必须是在微信支付中配置过的
function getWechatIntance($body, $out_trade_no, $fee, $notify_url, $openid)
{
    $obj = WechatService::WeChatPay();
    $pay_res = $obj->createOrder(['body' => $body, 'nonce_str' => date('YmdHis'), 'out_trade_no' => $out_trade_no, 'total_fee' => $fee, 'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], 'trade_type' => 'JSAPI', 'notify_url' => $notify_url, 'sign_type' => 'MD5', 'openid' => $openid]);
    $payjsparam = $obj->createParamsForJsApi($pay_res['prepay_id']);
    return $payjsparam;
}

//获取发放收益实例
function getMemberFree()
{
    try {
        $obj = \member\MemberFreeBonus::getInstance();
        return $obj;
    } catch (Exception $e) {
        trigger_error($e->getMessage());
    }

}

//制作二维码
function makeQrcode($content, $path)
{
    \PHPQRCode\QRcode::png($content, $path, 'L', 4, 0);
    return $path;
}


function level($id)
{
    return Db::name('sys_level')->find($id)['title'] ?? '暂无等级';
}


function address($id)
{
    if ($id) {
        return Db::name('sys_address')->find($id)['area_name'];
    }

}

/**
 * 打印输出数据到文件
 * @param mixed $data 输出的数据
 * @param bool $force 强制替换
 * @param string|null $file
 */
function p($data, $force = false, $file = null)
{
    is_null($file) && $file = env('runtime_path') . date('Ymd') . ' . txt';
    $str = (is_string($data) ? $data : (is_array($data) || is_object($data)) ? print_r($data, true) : var_export($data, true)) . PHP_EOL;
    $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
}

function phone($id)
{
    return Db::name('store_member')->where('id', $id)->value('phone');
}

function usernamecc($id)
{
    return Db::name('store_member')->where('id', $id)->value('nickname');
}


/**
 * RBAC节点权限验证
 * @param string $node
 * @return bool
 */
function auth($node)
{
    return NodeService::checkAuthNode($node);
}

/**
 * 设备或配置系统参数
 * @param string $name 参数名称
 * @param bool $value 默认是null为获取值，否则为更新
 * @return string|bool
 * @throws \think\Exception
 * @throws \think\exception\PDOException
 */
function sysconf($name, $value = null)
{
    static $config = [];
    if ($value !== null) {
        list($config, $data) = [[], ['name' => $name, 'value' => $value]];
        return DataService::save('SystemConfig', $data, 'name');
    }
    if (empty($config)) {
        $config = Db::name('SystemConfig')->column('name,value');
    }
    return isset($config[$name]) ? $config[$name] : '';
}

/**
 * 日期格式标准输出
 * @param string $datetime 输入日期
 * @param string $format 输出格式
 * @return false|string
 */
function format_datetime($datetime, $format = 'Y年m月d日 H:i:s')
{
    return date($format, strtotime($datetime));
}

function format_time($datetime, $format = 'Y-m-d H:i:s')
{
    return date($format, $datetime);
}

/**
 * UTF8字符串加密
 * @param string $string
 * @return string
 */
function encode($string)
{
    list($chars, $length) = ['', strlen($string = iconv('utf - 8', 'gbk', $string))];
    for ($i = 0; $i < $length; $i++) {
        $chars .= str_pad(base_convert(ord($string[$i]), 10, 36), 2, 0, 0);
    }
    return $chars;
}

/**
 * UTF8字符串解密
 * @param string $string
 * @return string
 */
function decode($string)
{
    $chars = '';
    foreach (str_split($string, 2) as $char) {
        $chars .= chr(intval(base_convert($char, 36, 10)));
    }
    return iconv('gbk', 'utf - 8', $chars);
}

/**
 * 下载远程文件到本地
 * @param string $url 远程图片地址
 * @return string
 */
function local_image($url)
{
    return \service\FileService::download($url)['url'];
}

function username($id)
{
    $username = Db::name('store_member')->where(['id' => $id])->value('phone');
    return $username;
}

function name($id)
{
    $username = Db::name('store_member')->where(['id' => $id])->value('nickname');
    $username ? $username : '暂未设置';
    return $username;
}

function datetime($msg)
{
    if ($msg) {
        $time = date('Y-m-d H:i:s', $msg);

    } else {
        $time = '暂无';
    }
    return $time;
}

function adminname($msg)
{
    $name = Db::name('system_user')->where(['id' => $msg])->value('username');
    return $name ? $name : '暂无';

}

function get_share_num($id)
{
    return Db::name('store_member')->where('first_leader', $id)->count();
}

function getagentinfo($id)
{

        $name = Db::name('agent')->where(['id' => $id])->value('username');
        return $name ? $name : '无';


}


function getshopsinfo($id,$filename ='shop_name')
{

    $name = Db::name('store_shops')->where(['id' => $id])->value($filename);
    return $name ? $name : '无';


}
